const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const createThemeColorReplacerPlugin = require('./config/plugin.config')
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
var baseURL = process.env.VUE_APP_ADMIN_FRONT
//生产环境下打包保留debugger
//const TerserPlugin = require('terser-webpack-plugin')
//生产环境下组件获取路径 __file ;
const VueFilenameInjector = require('@d2-projects/vue-filename-injector')
const CopyWebpackPlugin = require('copy-webpack-plugin')

function resolve(dir) {
    console.info('__dirname:' + __dirname + ',' + dir)

    return path.join(__dirname, dir)
}

let productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i
const isProd = process.env.NODE_ENV === 'production'

// webpack build externals
const prodExternals = {
    // key表示包名(import foo from 'xx' 里的xx)
    // value表示window下的全局变量名(库暴露出来的namespace,可查lib对应的webpack配置里的library字段)
    vue: 'Vue',
    axios: 'axios',
    echarts: 'echarts',
    'vue-router': 'VueRouter',
    vuex: 'Vuex',
    moment: 'moment',
    codemirror: 'CodeMirror',
    '@antv/g2': 'G2',
    '@antv/data-set': 'DataSet',
    'ant-design-vue': 'antd',
    html2canvas: 'html2canvas',
}

// publicPath: "/jpaas",
// vue.config.js
const vueConfig = {
    publicPath: baseURL,
    configureWebpack: {
        externals: prodExternals,
        plugins: [
            // Ignore all locale files of moment.js
            new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
            new webpack.IgnorePlugin(/moment\//),
            // new BundleAnalyzerPlugin({
            //     analyzerPort: 6014,
            // }),
            new MonacoWebpackPlugin({
                languages: [],
            }),
            new CopyWebpackPlugin([
                {
                    from: './node_modules/@lowcode/jpaas-common-lib/lib/commonImages/',
                    to: 'commonImages/',
                    toType: 'dir',
                },
            ]),
            new HtmlWebpackPlugin({
                // 指定入口 HTML 模板文件路径
                template: './public/index.html',
                // 添加 defer 属性到 script 标签
                scriptLoading: 'defer',
                templateParameters: { BASE_URL: '/jpaas/' },
                publicPath: '/jpaas',
            }),
        ],
    },
    assetsDir: 'static',
    chainWebpack: (config) => {
        // config.entry('polyfill').add('@babel/polyfill');
        config.resolve.alias
            .set('@$', resolve('src'))
            .set('@static', resolve('static'))
            .set('@public', resolve('public'))
            .set('@img', resolve('static/img'))
        const svgRule = config.module.rule('svg')
        svgRule.uses.clear()
        svgRule
            .oneOf('inline')
            .resourceQuery(/inline/)
            .use('vue-svg-icon-loader')
            .loader('vue-svg-icon-loader')
            .end()
            .end()
            .oneOf('external')
            .use('file-loader')
            .loader('file-loader')
            .options({
                name: 'assets/[name].[hash:8].[ext]',
            })

        // if (isProd) {
        //     config.plugin('CompressionPlugin').use('compression-webpack-plugin', [
        //         {
        //             algorithm: 'gzip',
        //             // 要压缩的文件（正则）
        //             test: productionGzipExtensions,
        //             // 最小文件开启压缩
        //             threshold: 10240,
        //             minRatio: 0.8,
        //             // deleteOriginalAssets: true//压缩完是否删除源文件
        //         },
        //     ]);
        // }

        VueFilenameInjector(config, {
            propName: '__source', // default
        })
    },

    css: {
        loaderOptions: {
            less: {
                lessOptions: {
                    javascriptEnabled: true,
                },
            },
        },
    },

    devServer: {
        // development server port 8000
        port: 8002,
        disableHostCheck: true,
        proxy: {
            '/api': {
                target: 'http://139.159.182.202:8000/api',
                // target: 'http://139.159.182.202:8000/api',
                pathRewrite: { '^/api': '' },
                ws: false,
                changeOrigin: true,
            },
        },
    },

    // disable source map in production
    productionSourceMap: false,
    lintOnSave: undefined,
    // babel-loader no-ignore node_modules/*
    transpileDependencies: [],
}

// 如果你不想在生产环境开启换肤功能，请打开下面注释
// if (process.env.VUE_APP_PREVIEW === 'true') {
// add `ThemeColorReplacer` plugin to webpack plugins
vueConfig.configureWebpack.plugins.push(createThemeColorReplacerPlugin())
vueConfig.configureWebpack.plugins.push(new MonacoWebpackPlugin())
// }

module.exports = vueConfig
